package com.lv.suyiyong.hfr.ui

import android.content.Intent
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.BaseActivity
import com.lv.common.im.GenerateTestUserSig
import com.lv.common.im.push.OfflineMessageDispatcher
import com.lv.common.ktx.viewLifeCycleOwner
import com.lv.common.network.model.DataResult
import com.lv.common.thirdparty.ShareUtils
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.LiveEventUtils
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.service.bean.AroutBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.KeyLoginReqBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.suyiyong.hfr.BuildConfig
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.databinding.ActivityLoginOneKeyBinding
import com.lv.suyiyong.hfr.moudel.MainViewModel
import com.lv.suyiyong.hfr.utils.login.BaseUIConfig
import com.lv.suyiyong.hfr.utils.login.Constant
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper
import com.mobile.auth.gatewayauth.ResultCode
import com.mobile.auth.gatewayauth.TokenResultListener
import com.mobile.auth.gatewayauth.model.TokenRet
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUICallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import org.koin.androidx.viewmodel.ext.android.viewModel


@Route(path = ARoutUtils.OneKeyLoginActivityURL)
class OneKeyLoginActivity : BaseActivity<ActivityLoginOneKeyBinding>() {
    @Autowired(name = ARoutUtils.AROUT_TAG)
    @JvmField
    var mTagARouter: AroutBean? = null
    private var mTokenResultListener: TokenResultListener? = null
    private var mPhoneNumberAuthHelper: PhoneNumberAuthHelper? = null
    private var mUIConfig: BaseUIConfig? = null

    //    private var mTagARouter: String? = null
    private val viewModel: MainViewModel by viewModel()
    private val viewModelService: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())

    override fun getLayoutRes() = R.layout.activity_login_one_key
    override fun initView() {
        super.initView()
        ARouter.getInstance().inject(this)
        UserDbHelper.deleteUserInfo(this)
        //清除Token
        YgxUtilsKt.setAppToken("", "", "")
        OfflineMessageDispatcher.updateBadge(this@OneKeyLoginActivity, 0)

        TUILogin.logout(object : TUICallback() {
            override fun onSuccess() {}
            override fun onError(errorCode: Int, errorMessage: String) {}
        })
        V2TIMManager.getConversationManager().removeConversationListener(null)
//        mTagARouter = intent.getStringExtra(ARoutUtils.SearchGoodsActivity)

//        initStatusBar(this, true, true)
        sdkInit(BuildConfig.AUTH_SECRET)
        mUIConfig =
            BaseUIConfig.init(
                Constant.CUSTOM_XML,
                this@OneKeyLoginActivity,
                viewModel,
                viewLifeCycleOwner,
                mPhoneNumberAuthHelper,
                mTagARouter
            )
        oneKeyLogin()
//        mBinding.apply {
//            vm = viewModel
////            StatusBarUtil.setHeightAndPadding(this@OneKeyLoginActivity, ivBack)
////            ivBack.setOnClickListener { this }
////            ivBack.setSafeListener { viewModel.repoLogin() }
//            btnLogin.setSafeListener {
//                configLoginTokenPort()
//                getLoginToken(5000)
//            }
//
//        }
//        LoginUtils.configLoginTokenPort(this)
//        LoginUtils.getLoginToken(5000,this@OneKeyLoginActivity)
    }

    fun sdkInit(secretInfo: String?) {
        mTokenResultListener = object : TokenResultListener {
            override fun onTokenSuccess(s: String) {
                loadFinished()
                LogUtils.e("获取token成功：$s")
                var tokenRet: TokenRet? = null
                try {
                    tokenRet = TokenRet.fromJson(s)
                    if (ResultCode.CODE_START_AUTHPAGE_SUCCESS == tokenRet.code) {
                        LogUtils.e("TAG", "唤起授权页成功：$s")
                    }
                    if (ResultCode.CODE_SUCCESS == tokenRet.code) {
                        LogUtils.e("TAG", "获取token成功：$s")
//                        getResultWithToken(tokenRet.token)
                        gokeyToLand(tokenRet.token)
                        mPhoneNumberAuthHelper!!.setAuthListener(null)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onTokenFailed(s: String) {
                LogUtils.e("获取token失败：$s")
                loadFinished()
                mPhoneNumberAuthHelper!!.hideLoginLoading()
                var tokenRet: TokenRet? = null
                try {
                    tokenRet = TokenRet.fromJson(s)
                    if (ResultCode.CODE_ERROR_USER_CANCEL == tokenRet?.getCode()) {
                        //模拟的是必须登录 否则直接退出app的场景
//                        finish()
                    } else {
//                        showToast(this@OneKeyLoginActivity, "一键登录失败切换到其他登录方式")
                        ARouter.getInstance().build(ARoutUtils.LoginActivityURL)
                            .withParcelable(ARoutUtils.AROUT_TAG, mTagARouter).navigation()
//                        val pIntent = Intent(
//                            this@OneKeyLoginActivity,
//                            LoginActivity::class.java
//                        )
//                        startActivityForResult(pIntent, 1002)
//                        finish()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                mPhoneNumberAuthHelper!!.quitLoginPage()
                mPhoneNumberAuthHelper!!.setAuthListener(null)
            }
        }
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenResultListener)
        mPhoneNumberAuthHelper?.reporter?.setLoggerEnable(true)
        mPhoneNumberAuthHelper?.setAuthSDKInfo(secretInfo)

    }

    private fun gokeyToLand(token: String?) {
        if (!token.isNullOrEmpty()) {
            val keyLoginReqBody = KeyLoginReqBody(token)
            keyToLand(keyLoginReqBody)
        }
    }

    private fun keyToLand(keyLoginReqBody: KeyLoginReqBody) {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async {
                    viewModelService.keyToLand(keyLoginReqBody)
                }.await()
            parseKeyToLandResult(result)
        }
    }

    private fun parseKeyToLandResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                data?.let { login(it) }
            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }

    override fun initConfig() {
        super.initConfig()
    }

    private fun login(res: UserInfo) {
        YgxUtilsKt.setAppToken(res.token, res.refreshtoken, res.id)

        // 在用户 UI 点击登录的时候调用
        TUILogin.login(
            this@OneKeyLoginActivity,
            GenerateTestUserSig.SDKAPPID,
            res.txaccid,
            res.txaccidpassword,
            object : TUICallback() {
                override fun onError(code: Int, desc: String) {
                    LogUtils.e("onError")
                }

                override fun onSuccess() {
                    UserDbHelper.insertUserInfo(this@OneKeyLoginActivity, res)
                    LogUtils.e("登录onSuccess")
                    mPhoneNumberAuthHelper?.removeAuthRegisterViewConfig()
                    mPhoneNumberAuthHelper?.quitLoginPage()
                    YgxUtilsKt.sendMessgeToSelf(res.txaccid, res.phone)

//                    mTagARouter?.apply {
//                        YgxSYYADKt.LoginToTarget(mTagARouter, res)
//                    }

                    finish()
                }
            })
    }

    override fun initData() {
        super.initData()
        //收到消息关闭
        LiveEventBus
            .get(LiveEventUtils.FINISH_ONEKEYLOGINACTIVITY_KEY, String::class.java)
            .observe(this) {
                finish()
            }//        LiveEventBus.get(
//            ThreeLandingEvent::class.java,
//        ).observe(
//            this
//        ) { s ->
//            if (s != null) {
//                if (s.tag == 1) {
//                    ShareUtils.get().login(this, ShareUtils.QQ)
//                        .setOnAliCallBackListener({ v, openId ->
//                            if (!openId.isNullOrEmpty()) {
//                                val threedLoginReqBody =
//                                    ThreedLoginReqBody(openId, s.tag.toString())
//                                viewModel.threeLanding(threedLoginReqBody)
//                            }else{
//
//                            }
//
//                        }, {})
//                } else {
//                    LogUtils.e("三方登录回调了== ${s.tag}==${s.openid}")
//                    val openid = s.openid
//                    val threedLoginReqBody = ThreedLoginReqBody(openid, s.tag.toString())
//                    viewModel.threeLanding(threedLoginReqBody)
//                }
////                finish()
//            }
//        }
    }

    /**
     * 进入app就需要登录的场景使用
     */
    private fun oneKeyLogin() {
        mPhoneNumberAuthHelper =
            PhoneNumberAuthHelper.getInstance(applicationContext, mTokenResultListener)
        mPhoneNumberAuthHelper?.checkEnvAvailable()
        mUIConfig!!.configAuthPage()
        //用户控制返回键及左上角返回按钮效果
        mPhoneNumberAuthHelper?.userControlAuthPageCancel()
        //用户禁用utdid
        //mPhoneNumberAuthHelper.prohibitUseUtdid();
        //授权页是否跟随系统深色模式
        mPhoneNumberAuthHelper?.setAuthPageUseDayLight(true)
        //授权页物理返回键禁用
        //mPhoneNumberAuthHelper.closeAuthPageReturnBack(true);
        //横屏水滴屏全屏适配
        mPhoneNumberAuthHelper?.keepAuthPageLandscapeFullSreen(true)
        //授权页扩大协议按钮选择范围至我已阅读并同意
        //mPhoneNumberAuthHelper.expandAuthPageCheckedScope(true);
        getLoginToken(5000)
    }

    /**
     * 拉起授权页
     *
     * @param timeout 超时时间
     */
    fun getLoginToken(timeout: Int) {
        mPhoneNumberAuthHelper!!.getLoginToken(this, timeout)
        startLoading("授权中……")
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
//        if (requestCode == 1002) {
//            if (resultCode == 1) {
////                mTvResult.setText("登陆成功：" + data.getStringExtra("result"))
////                mTvResult.setMovementMethod(ScrollingMovementMethod.getInstance())
//            } else {
//                //模拟的是必须登录 否则直接退出app的场景
//                finish()
//            }
//        }
        if (data != null) {
            //QQ回调
            ShareUtils.get().onQqActivityResult(requestCode, resultCode, data)
        }
    }

    override fun onResume() {
        super.onResume()
        mUIConfig!!.onResume()
    }

//    fun showLoadingDialog(hint: String?) {
//        if (mProgressDialog == null) {
//            mProgressDialog = ProgressDialog(this)
//            mProgressDialog?.setProgressStyle(ProgressDialog.STYLE_SPINNER)
//        }
//        mProgressDialog?.setMessage(hint)
//        mProgressDialog?.setCancelable(true)
//        mProgressDialog?.show()
//    }
//
//    fun hideLoadingDialog() {
//        mProgressDialog?.dismiss()
//    }

//    fun getResultWithToken(token: String?) {
//        ExecutorManager.run(Runnable {
//            val result: String = getPhoneNumber(token)
//            this@OneKeyLoginDelayActivity.runOnUiThread(Runnable {
//                mTvResult.setText("登陆成功：$result")
//                mTvResult.setMovementMethod(ScrollingMovementMethod.getInstance())
//                mLoginBtn.setVisibility(View.GONE)
//                mPhoneNumberAuthHelper!!.quitLoginPage()
//            })
//        })
//    }

}